//
// Created by mouse on 2019/11/12.
//

#ifndef NODEMCU_MQTT_H
#define NODEMCU_MQTT_H

#include <Arduino.h>
#include <ArduinoJson.h>
#include <Scheduler.h>
#include <MQTT.h>
#include "Utils.h"
#include "app_config.h"
#include "app_log.h"

#define SEND_BUFFER_SIZE 1024

#define MQTT_TOPIC_SYS "sys"
#define MQTT_TOPIC_USER "user"

namespace MqttUtils {

    typedef struct
    {
        char title[16];
        char product[32];
        char device[32];
        char function[8];
        char item[16];
    } TopicEntity;

    MqttUtils::TopicEntity *toTopic(String topicStr);

    String toTopicString(MqttUtils::TopicEntity *topic);

    String toTopicString(const char *title,
                         const char *product,
                         const char *device,
                         const char *function,
                         const char *item);
}

typedef struct
{
    String topic;
    MQTTClientCallbackSimple callback;
    int qos = 1;
} RecvCallback;

class NetworkTask : public Task
{
private:
    WiFiClient *wiFiClient;
    MQTTClient *mqttClient;

    static void messageReceived(String &topic, String &payload);

    void mqttConnectSync();

    void setWill();

    void reportDevice();

public:
    NetworkTask();

    ~NetworkTask();

    MQTTClient *getMqttClient();

    void addSubscribeTopic(String topic, MQTTClientCallbackSimple cb, int qos);

    void removeSubscribeTopic(String topic);

    void messageSend(String &topic, String &payload, bool retained, int qos);

protected:
    virtual void setup() override;

    virtual void loop() override;
};


#endif //NODEMCU_MQTT_H
